package com.kaifamiao.servlet;

import com.kaifamiao.entity.Customer;
import com.kaifamiao.jdbc.helper.JdbcHelper;
import com.kaifamiao.jdbc.helper.RowHolder;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDate;

@WebServlet("/customer/edit/page")
public class CustomerEditPageServlet extends HttpServlet {

    private JdbcHelper helper;
    private RowHolder<Customer> holder;
    private String select;

    @Override
    public void init() throws ServletException {
        helper = JdbcHelper.getInstance();
        holder = rs -> {
            Customer c = new Customer();
            c.setId( rs.getInt( "id" ) );
            c.setUsername( rs.getString( "username" ) );
            c.setNickname( rs.getString( "nickname" ) );
            return c ;
        };
        select = "SELECT id, username, nickname FROM t_customers WHERE id = ?";
    }

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding( "UTF-8" );
        response.setCharacterEncoding("UTF-8");

        response.setContentType("text/html; charset=UTF-8");
        PrintWriter out = response.getWriter();
        // 链接外部样式文件
        out.println( "<link rel=\"stylesheet\" href=\"/css/customer.css\">");

        String idString = request.getParameter( "id" );
        if( idString == null || idString.isBlank() ) {
            out.println( "<p>被删除的数据不存在</p>" );
            return;
        }

        Integer id = Integer.valueOf(idString);
        // 根据参数传递过来的id值查找指定的用户数据
        Customer c = helper.single( select, holder, id);

        out.println( "<p>修改用户信息</p>" );
        out.println( "<form action=\"/customer/edit/action\" method=\"post\">");
        out.println( "<input type=\"hidden\" name=\"id\" value=\"" + c.getId() + "\">");
        out.println( "<p>用户名:<input type=\"text\" name=\"username\" value=\"" + c.getUsername()+ "\"></p>" );
        out.println( "<p>昵称:<input type=\"text\" name=\"nickname\" value=\"" + c.getNickname() + "\"></p>" );
        out.println( "<button type=\"submit\">确定</button>" );
        out.println( "</form>");
    }

    @Override
    public void destroy() {
        helper.release();
    }
}
